<?php

namespace Module\Cms;

use Base\Contents;
use W3\Router;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 处理搜索
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Search extends Contents
{
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {
		# 定义变量默认数据
        $this->parameter([

			# 设置主体
			'main' => 'search',
			
			# 分页大小
		    'pageSize' => 20,
			
			# 主题文件
            'themeFile' => 'search',
			
		], true);
		
		# 默认搜索引擎
        !action_exists('search.select') && add_action('search.select', function ($widget, $select) 
		{
            $keywords = $widget->parameter->keywords = $widget->request->filter('url', 'search')->keywords;
			$searchQuery = '%' . str_replace(' ', '%', $keywords) . '%';

            /** 按post查询 */
            return $select
		        ->where('table.contents.type = ?', 'post')
			    ->where('table.contents.status = ?', 'publish')
                ->where('table.contents.title LIKE ? OR table.contents.text LIKE ?', $searchQuery, $searchQuery);
        });
	}

    public function execute()
    {
        $select = $this->select();
		$keywords = $this->parameter->keywords;
		
        /** 计算数目 */
		$total = $select->count();
		$page = $this->request->get('page', 1);
		$pageUrl = Router::buildUrl('search_page', ['keywords' => urlencode($keywords),'page'=>'%page%']);

		$select
		    ->page($page, $this->parameter->pageSize)
		    ->get([$this, 'push']);

		$this->parameter([
		
		    # 设置关键词
		    'keywords' => $keywords,
			
			# 设置描述
		    'description' => $keywords,
			
			# 设置标题
		    'title' => $keywords,
		
		    # 设置缩略名
		    'alias' => $keywords,
			
			# 当前页数
			'page' => $page, 
			
			# 内容总数
			'total' => $total, 
			
			# 页面Url
			'pageUrl' => $pageUrl,

		]);
    }
}

